const { ref } = Vue

/**
 *
 * @param {HashChangeEvent} event
 */
Route.prototype.handleHasChange = function (event) {
  let url = new URL(event.newURL)
  let hash = url.hash.replace(/\?.*/gi, '').replace('#', '')
  let param = url.hash.split('?')[1] || ''

  if (this.hash === hash) return

  if (!hash) hash = 'user'

  this.query = this.parseQuery(param)
  this.route = url.pathname
  this.hash.value = hash

  // 判断组件是否已经注册
  if (this.componentNames.includes(hash)) {
    app._instance.data.currentComponent = hash
    return
  }
  // 加载对应组件
  import(`${config.RP}/html/route/${hash}/${hash}.js`)
    .then((res) => {
      res.default
        .load()
        .then((res) => {
          this.componentNames.push(hash)
          console.log('app._instance.isMounted: ', app._instance.isMounted)
          app._instance.data.currentComponent = hash
        })
        .catch((err) => {
          console.log('handleHasChange load error', err)
        })
    })
    .catch((err) => {
      ElMessage.error('加载路由组件出错!')
      console.warn('Load Route HTML err: ', err)
    })
}

/**
 *
 * @param {string} param
 * @returns
 */
Route.prototype.parseQuery = function (param) {
  let query = {}
  new URLSearchParams(param).forEach((value, key) => {
    query[key] = value
  })

  return query
}

Route.prototype.to = function (hash, query = {}) {
  let param = ''
  for (const key in query) {
    if (Object.hasOwnProperty.call(query, key)) {
      param += `${key}=${query[key]}`
    }
  }

  location.hash = `#${hash}?${param}`
}

/**
 *初始化
 */
Route.prototype.init = function () {
  // 手动解析ｕrl
  this.handleHasChange({ newURL: window.location.href })
  // 绑定监听
  window.addEventListener('hashchange', this.handleHasChange.bind(this))
}

function Route() {
  this.route = ''
  this.hash = ref('')
  this.query = {}
  this.componentNames = []

  this.init()
}

const route = new Route()

export default route
